<?php

namespace app\system\controller\customer;

use app\common\controller\System;
use app\system\controller\daily\Throwable;
use hehe\Str;
use hehe\Trade;
use think\facade\Db;


class Product extends System {
    /**
     * Goods模型对象
     * @var object
     */
    protected object $model;

    protected string|array $defaultSortField = 'id,desc';

    protected array|string $preExcludeFields = ['id', 'create_time'];

    protected string|array $quickSearchField = [''];
    
    protected array $noNeedLogin = ['getProductSni', 'getSelectProductSni', 'addOrderSni'];

    public function initialize(): void {
        parent::initialize();
        $this->model = new \app\system\model\customer\Product();
    }


    public function getProductInfo(){
        $params = $this->request->param();
        $product_ids = [];
        if(empty($params['product_ids'])) $this->success('', []);
        foreach($params['product_ids'] as $val){
            $product_ids[] = $val[1];
        }
//        print_r($product_ids); die;
        $product = db::name('product')->field('*')->whereIn('id', $product_ids)->select();
        $this->success('', $product);
    }


    public function getProduct(){
        $params = $this->request->param();
        $category = db::name('product_category')->where(['customer_id' => $params['customer_id']])->select();
        $category_ids = [];
        foreach($category as $val){
            $category_ids[] = $val['id'];
        }
        $product = db::name('product')->whereIn('category_id', $category_ids)->select();

        $data = [];
        foreach($category as $key => $val){
            $data[$key]['value'] = 'category_id_' . $val['id'];
            $data[$key]['label'] = $val['name_cn'];
            foreach($product as $v){
                if($val['id'] == $v['category_id']){
                    $data[$key]['children'][] = [
                        'value' => $v['id'],
                        'label' => $v['name_supplier'] . '(' . $v['specification_supplier'] . ')'
                    ];
                }

            }
        }

        $this->success('', $data);
    }
    
    public function getProductSni(){
        $params = $this->request->param();
        $category = db::name('product_category')->where(['customer_id' => 14])->select();
        $category_ids = [];
        foreach($category as $val){
            $category_ids[] = $val['id'];
        }
        $product = db::name('product')->whereIn('category_id', $category_ids)->select();

        $data = [];
        foreach($category as $key => $val){
            $data[$key]['value'] = 'category_id_' . $val['id'];
            $data[$key]['label'] = $val['name_en'];
            foreach($product as $v){
                if($val['id'] == $v['category_id']){
                    $data[$key]['children'][] = [
                        'value' => $v['id'],
                        'label' => $v['name'] . '(' . $v['code'] . ')'
                    ];
                }

            }
        }

        $this->success('', $data);
    }
    
    public function getSelectProductSni(){
        $params = $this->request->param();
        $product_ids = [];
        if(empty($params['product_ids'])) $this->success('', []);
        foreach($params['product_ids'] as $val){
            $product_ids[] = $val[1];
        }
        
        

        $product = db::name('product')->field('*')->whereIn('id', $product_ids)->select()->toArray();
        
        foreach($product as $key => $val){
            if(isset($params['product'])){
                foreach($params['product'] as $v){
                    if(!empty($v['value']) && $val['id'] == $v['id']){
                        $product[$key]['value'] = $v['value'];
                    }
                }
            }
            
            
            $product[$key]['key'] = $val['name'] . '(' . $val['code'] . ')';
        }
        
        $this->success('', $product);
    }
    
    
    public function addOrderSni(): void {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            if (!$data) {
                $this->error(__('数据不能为空'));
            }

            $product = empty($data['product']) ? [] : $data['product'];

            // if(empty($data['customer_id'])) $this->error(__('请选择客户'));
            // if($this->filter['id'] != 2 && empty($data['supplier_id'])) $this->error(__('请选择供货商'));
            // if(empty($data['type'])) $this->error(__('请选择订单类型'));
            $data['create_time'] = empty($data['create_time']) ? $this->timestamp : strtotime($data['create_time']);

            $result = false;
            $this->model->startTrans();
            try {
                $category_ids = [];
                foreach($product as $val){
                    if(!in_array($val['category_id'], $category_ids)) $category_ids[] = $val['category_id'];
                }
                $category = db::name('product_category')->whereIn('id', $category_ids)->select();
                $info = [];
                foreach($category as $val){
                    foreach($product as $v){
                        if($val['id'] == $v['category_id']){
                            $info['supplier_' . $val['supplier_id']]['product'][] = $v;
                            $info['supplier_' . $val['supplier_id']]['category'] = $val;
                        }
                    }
                }
                foreach($info as $key => $val){
                    $order_count = db::name('customer_order')->whereDay('create_time', date('Y-m-d', $data['create_time']))->count();
                    if($order_count){
                        $no = $order_count + 1;
                        $contract = 'YN' . date('ymd', $data['create_time']) . $no;
                    }else{
                        $contract = 'YN' . date('ymd', $data['create_time']) . '1';
                    }
                    $order_insert = [
                        'filter_id' => $this->filter['id'],
                        'customer_id' => $val['category']['customer_id'],
                        'supplier_id' => $val['category']['supplier_id'],
                        'out_trade_no' => Trade::generateTradeNoShort(),
                        'order_type' => '出口',
                        'trade_type' => '买入交易',
                        'create_time' => $data['create_time'],
                        'contract' => $contract,
                        'note' => 'sni系统下单',
                        'source' => 'sni'
                    ];
                    $order_id = db::name('customer_order')->insertGetId($order_insert); // 写入订单
                    $order_detail = [];
                    foreach($val['product'] as $v){ // 记录订单详细内容
                        $order_detail[] = [
                            'order_id' => $order_id,
                            'product_id' => $v['id'],
                            'quantity' => $v['value'] * $this->multiply,
                        ];
                    }
                    $result = db::name('customer_order_detail')->insertAll($order_detail);
                }
                $this->model->commit();
            } catch (Throwable $e) {
                $this->model->rollback();
                $this->error($e->getMessage());
            }
            if ($result !== false) {
                $this->success(__('Added successfully'));
            } else {
                $this->error(__('No rows were added'));
            }
        }
        $this->error(__('Parameter error'));
    }


    /**
     * 查看
     * @throws Throwable
     */
    public function index(): void {
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->param('select')) {
            $this->select();
        }
        list($where, $alias, $limit, $order) = $this->queryBuilder();
        $params = $this->request->param();
        $customer_id = $params['customer_id'];
        $res = $this->model
            ->field($this->indexField)
            ->withJoin(['group' => function($query) use ($customer_id){
                $query->where(['customer_id' => $customer_id]);
            }], 'LEFT')
            ->with(['supplier'])
            ->alias($alias)
            ->where($where)->order($order)->paginate($limit);


        $list = $res->items();
        if($this->request->has('select')){
            foreach($list as $key => $val){

            }
        }

        foreach($list as $key => $val){
            $list[$key]['buy_price'] /= $this->multiply;
            $list[$key]['sale_price'] /= $this->multiply;
        }

        $params = $this->request->param();
        $customer = db::name('customer')->where(['id' => $params['customer_id']])->find();


        $this->success('', [
            'list' => $list,
            'total' => $res->total(),
            'remark' => get_route_remark(),
            'customer' => $customer
        ]);
    }

    public function add(): void {
        if ($this->request->isPost()) {
            $data = $this->request->post();

            $data = $this->excludeFields($data);
            if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                $data[$this->dataLimitField] = $this->auth->id;
            }

            if(empty($data['group_id'])) $this->error('请选择产品分类');
            if(empty($data['name'])) $this->error('请输入产品名称');
            if(empty($data['buy_currency'])) $this->error('请选择购买币种');
            if(empty($data['buy_price'])) $this->error('请输入购买价格');
            if(empty($data['sale_currency'])) $this->error('请选择销售币种');
            if(empty($data['sale_price'])) $this->error('请选择销售价格');

            $data['buy_price'] *= $this->multiply;
            $data['sale_price'] *= $this->multiply;
            $data['create_time'] = $this->timestamp;

            $result = false;
            $this->model->startTrans();
            try {
                // 模型验证
                if ($this->modelValidate) {
                    $validate = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                    if (class_exists($validate)) {
                        $validate = new $validate;
                        if ($this->modelSceneValidate) $validate->scene('add');
                        $validate->check($data);
                    }
                }
                $result = $this->model->save($data);
                $this->model->commit();
            } catch (Throwable $e) {
                $this->model->rollback();
                $this->error($e->getMessage());
            }
            if ($result !== false) {
                $this->success(__('Added successfully'));
            } else {
                $this->error(__('No rows were added'));
            }
        }

        $this->error(__('Parameter error'));
    }



    public function edit(): void
    {
        $id  = $this->request->param($this->model->getPk());
        $row = $this->model->find($id);

        $dataLimitAdminIds = $this->getDataLimitAdminIds();
        if ($dataLimitAdminIds && !in_array($row[$this->dataLimitField], $dataLimitAdminIds)) {
            $this->error(__('You have no permission'));
        }

        if ($this->request->isPost()) {
            $data = $this->request->post();
            if (!$data) {
                $this->error(__('Parameter %s can not be empty', ['']));
            }

            $data   = $this->excludeFields($data);

            if(empty($data['group_id'])) $this->error('请选择产品分类');
            if(empty($data['name'])) $this->error('请输入产品名称');
            if(empty($data['buy_currency'])) $this->error('请选择购买币种');
            if(empty($data['buy_price'])) $this->error('请输入购买价格');
            if(empty($data['sale_currency'])) $this->error('请选择销售币种');
            if(empty($data['sale_price'])) $this->error('请选择销售价格');
            if(empty($data['supplier_id'])) $this->error('请选择供应商');

            $data['buy_price'] *= $this->multiply;
            $data['sale_price'] *= $this->multiply;
            $data['update_time'] = $this->timestamp;
//            print_r($data);die;
            $result = false;
            $this->model->startTrans();
            try {
                $result = $row->save($data);
                $this->model->commit();
            } catch (Throwable $e) {
                $this->model->rollback();
                $this->error($e->getMessage());
            }
            if ($result !== false) {
                $this->success(__('Update successful'));
            } else {
                $this->error(__('No rows updated'));
            }
        }
        $row = $row->toArray();


        $row['buy_price'] /= $this->multiply;
        $row['sale_price'] /= $this->multiply;

        $row['customer_id'] = db::name('customer_product_group')->where(['id' => $row['group_id']])->value('customer_id');

        $this->success('', [
            'row' => $row
        ]);
    }



    /**
     * 删除报价单
     */
    public function delQuotationFile(): void {
        $id = $this->request->param('id');
        $update = [
            'quotation_file' => null,
            'update_time' => $this->timestamp
        ];
        db::name('business_quotation')->where(['id' => $id])->update($update);
        $this->success();
    }

    /**
     * 上传报价单
     */
    public function setQuotationFile(): void{
        $param = $this->request->post();
//        print_r($param);
        $quotation_file = json_encode($param['quotation_file']);
        $update = [
            'quotation_file' => $quotation_file,
            'update_time' => $this->timestamp
        ];
        db::name('business_quotation')->where(['id' => $param['id']])->update($update);
        $this->success();
    }


    /**
     * 删除备注
     */
    public function delNote(){
        $param = $this->request->param();
        db::name('business_quotation_note')->where(['id' => $param['id']])->delete();
        $this->success();
    }

    /**
     * 添加备注
     */
    public function addNote(){
        $param = $this->request->param();
        $param['admin_id'] = $this->auth->id;
        $param['create_time'] = $this->timestamp;
        $note_id = db::name('business_quotation_note')->insertGetId($param);
        if($note_id){
            $this->success('', [
                'id' => $note_id,
                'content' => $param['content'],
                'admin' => [
                    'username' => $this->auth->username
                ]

            ]);
        }else{
            $this->error();
        }
    }

    /**
     * 隐藏报价
     */
    public function hideQuotation(){
        $param = $this->request->param();
        db::name('business_quotation')->where(['id' => $param['id']])->update(['hide' => 1]);
        $this->success();
    }
    /**
     * 显示报价
     */
    public function showQuotation(){
        $param = $this->request->param();
        db::name('business_quotation')->where(['id' => $param['id']])->update(['hide' => 0]);
        $this->success();
    }


































}